<script lang="ts" setup>
import {createRoleUserAPI, getRoleDetailAPI, getTreeListAPI, updateRoleAPI} from '@/apis/system';
import type { AuthData, RoleParams } from '@/types/system';
import { ElMessage, type ElTree, type FormInstance, type FormRules } from 'element-plus';
import {onMounted, ref} from 'vue';
import router from "@/router";
import {useRoute} from "vue-router";

// 1. 第一页
const activeStep = ref(0)
const roleFormRef = ref<FormInstance>()
const roleForm = ref<RoleParams>({
  roleName: '',
  remark: '',
  perms: []
})
const roleRules = ref<FormRules<RoleParams>>({
  roleName: [
    {required: true, message: '请输入角色的名称'}
  ]
})

// 2. 第二页
const treeList = ref<AuthData[]>([]) // 权限树形列表
const treeRef = ref<InstanceType<typeof ElTree>[]>()
// 获取功能权限列表
const getTreeList = async () => {
  const res = await getTreeListAPI()
  treeList.value = res.data
  // console.log(treeList.value)
}
getTreeList()

// 3. 第三页
const disabledTreeRef = ref<InstanceType<typeof ElTree>[]>()

// 4. 上一步
const decreaseStep = ()=>{
  if(activeStep.value === 0) return
  activeStep.value--
}
// 5. 下一步
const increaseStep = ()=>{
  if(activeStep.value === 2) return
  if(activeStep.value === 0){
    roleFormRef.value?.validate((valid: boolean)=>{
      if(valid){
        activeStep.value++
      }
    })
  } else if (activeStep.value === 1){
    // 先清空权限数组(防止重复添加)
    roleForm.value.perms = []
    // 遍历树数组
    treeRef.value?.forEach((tree)=>{
      roleForm.value.perms?.push(tree.getCheckedKeys() as any)
    })
    // 判断用户是否勾选权限点
    if (roleForm.value.perms.flat().length===0){
      ElMessage({
        message: '请至少勾选一个权限选项',
        type: 'error'
      })
    } else {
      activeStep.value++
      disabledTreeRef.value!.forEach((tree, index) => {
        // @ts-expect-error
        tree.setCheckedKeys(roleForm.value.perms[index])
      })
    }
  }
}
// 6. 确认添加
const addRole = async ()=>{
  if(roleId.value){ // 编辑
    await updateRoleAPI(roleForm.value)
  }else{ // 添加
    await createRoleUserAPI(roleForm.value)
  }
  ElMessage({
    message: `${roleId.value ? '修改' : '添加'}角色成功~`,
    type: 'success'
  })
  router.back()
}
// 7. 获取roleID
const roleId = ref()
const route = useRoute()
onMounted(()=>{
  roleId.value = route.query.roleId
  if (roleId.value){
    editRoleDetail(roleId.value)
  }
})
const editRoleDetail = async (id: string) => {
  const res = await getRoleDetailAPI(id)
  const {perms, remark, roleId, roleName} = res.data
  roleForm.value = { perms, remark, roleId, roleName }
  // 手动设置树组件的勾选
  treeRef.value?.forEach((tree, index) => {
    // @ts-expect-error
    tree.setCheckedKeys(perms[index])
  })
}

</script>

<template>
  <div class="add-role">
    <header class="add-header">
      <el-page-header :content="`${roleId ? '编辑' : '添加'}角色`" @back="$router.back()" />
    </header>
    <main class="add-main">
      <div class="step-container">
        <el-steps :active="activeStep" direction="vertical">
          <el-step title="角色信息" />
          <el-step title="权限信息" />
          <el-step title="检查并完成" />
        </el-steps>
      </div>
      <!-- 第一项 -->
      <div v-show="activeStep===0" class="form-container">
        <div class="title">角色信息</div>
        <div class="form">
          <el-form ref="roleFormRef" :model="roleForm" :rules="roleRules" class="form-box">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="roleForm.roleName" />
            </el-form-item>
            <el-form-item label="角色描述">
              <el-input v-model="roleForm.remark" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <!-- 第二项 -->
      <div v-show="activeStep === 1" class="form-container">
        <div class="title">权限配置</div>
        <div class="form">
          <div class="tree-wrapper">
            <div v-for="item in treeList" :key="item.id" class="tree-item">
              <div class="tree-title">{{ item.title }}</div>
              <el-tree ref="treeRef" :data="item.children" :props="{ label: 'title' }" check-strictly default-expand-all
                       highlight-current node-key="id" show-checkbox/>
            </div>
          </div>
        </div>
      </div>
      <!-- 第三项 -->
      <div v-show="activeStep === 2" class="form-container">
        <div class="title">检查并完成</div>
        <div class="form">
          <div class="info">
            <div class="form-item">角色名称：{{ roleForm.roleName }}</div>
            <div class="form-item">角色描述：{{ roleForm.remark }}</div>
            <div class="form-item">角色权限：</div>
            <div class="tree-wrapper">
              <div v-for="item in treeList" :key="item.id" class="tree-item">
                <div class="tree-title">{{ item.title }}</div>
                <el-tree ref="diabledTreeRef" :data="item.children" :highlight-current="false" :props="{ label: 'title', disabled: () => true }" default-expand-all
                         node-key="id" show-checkbox />
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button v-if="activeStep>0" @click="decreaseStep">上一步</el-button>
        <el-button v-if="activeStep<2" type="primary" @click="increaseStep">下一步</el-button>
        <el-button v-if="activeStep === 2" type="primary" @click="addRole">
          {{ roleId ? '确认修改' : '确认添加' }}
        </el-button>
      </div>
    </footer>
  </div>
</template>


<style lang="scss" scoped>
.add-role {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    position: fixed;
    top: 64px;
    bottom: 88px;
    width: 100%;
    overflow-y: auto;
    background: #f4f6f8;
    padding: 20px 30px;
    display: flex;

    .step-container {
      height: 400px;
      width: 200px;
    }

    .form-container {
      flex: 1;
      background-color: #fff;
      overflow-y: auto;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;
        }

        .info {
          font-size: 14px;
          color: #666;

          .form-item {
            margin-bottom: 20px;
          }
        }
      }

      .form-box {
        width: 600px;
        display: flex;
        flex-direction: column;
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
    z-index: 10001;
  }

  .tree-wrapper {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;

    .tree-item {
      flex: 1;
      padding: 0px 4px;
      text-align: center;

      .tree-title {
        background: #f5f7fa;
        text-align: center;
        padding: 10px 0;
        margin-bottom: 12px;
      }
    }
  }
}
</style>